package com.gupao.vip.trevor.queue.zookeeper;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * <h1></h1>
 * <p>
 * <b>描述：</b>
 * <br>
 * <br>
 * </p>
 *
 * @author Trevor
 * @version 1.0     2017年08月10日  15点21分
 */
public class ZKSessionFactory
{

    // 会话超时时间，设置为与系统默认时间一致
    private static final int SESSION_TIMEOUT = 60 * 1000;

    private ZooKeeper zooKeeper;

    // 创建 Watcher 实例
    private Watcher wh = event -> {
        System.out.println("WatchedEvent >>> " + event.toString());
        if (event.getType() == Watcher.Event.EventType.NodeDataChanged)
        {
            System.out.println(event.getPath());
        }
    };

    public ZKSession getZKSession() throws IOException
    {
        if(zooKeeper == null || !zooKeeper.getState().isAlive())
        {
            createZookeeper();
        }
        return new ZKSession(zooKeeper);
    }

    private void createZookeeper()
    {
        try
        {
            this.zooKeeper = new ZooKeeper("localhost:2184,localhost:2185,localhost:2186", SESSION_TIMEOUT, wh);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}
